﻿using System;
using System.Web.Mvc;
using System.Web.Routing;

using Fuse8.DomainFramework.Common.Locator;

using Fuse8.ContentManagementFramework.Domain;

namespace Fuse8.ContentManagementFramework.Administration.Controls
{
    public class FirstLoginActionFilterAttribute : ActionFilterAttribute
    {
        public const string FirstLoginFilterKey = "FirstLoginFilterKey";
        
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var user = DependencyServiceLocator.Current.GetInstance<ICmsContext>().ContextUser;

            if ((user != null) && !(user is CmsAnonimousUser) && user.HasInitialPassword)
            {
                RouteValueDictionary routeValueDictionary = new RouteValueDictionary(
                    new
                    {
                        id = user.Id,
                        returnUrl = filterContext.HttpContext.Request.Path
                    });

                routeValueDictionary["action"] = "ForcedPasswordChange";
                routeValueDictionary["controller"] = "CmsAccount";
                filterContext.Controller.TempData[FirstLoginFilterKey] = new object();

                filterContext.Result = new RedirectToRouteResult(routeValueDictionary);
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }
    }
}